package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1 判断上传的数据是否多段数据 二进制流格式
        if (ServletFileUpload.isMultipartContent(req)) {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            upload.setHeaderEncoding("UTF-8");
            upload.setFileSizeMax(1024*1024*10);
            // 解析上传的数据，得到每一个表单项FileItem
            try {
                List<FileItem> fileItems = upload.parseRequest(req);
                // 对fileItems迭代，每个对象调用isFormField方法判断是否是上传文件
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {
                        // 普通表单字段，则调用getFieldName、getString方法得到字段名段值
                        String fieldName = fileItem.getFieldName();
                        String value = fileItem.getString("UTF-8");
                        System.out.println(fieldName+":"+value);
                    } else {
                        // 为上传文件
                        String fieldName = fileItem.getFieldName();
                        // 文件名
                        String name = fileItem.getName();
                        System.out.println(fieldName + ":" + name);
                        String realPath = getServletContext().getRealPath("/files/");
                        System.out.println(realPath);
                        File file = new File(realPath);
                        if (!file.exists()) {
                            // 创建目录
                            file.mkdir();
                        }
                        File file1 = new File(realPath + name);
                        fileItem.write(file1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }
}
